// 设计链表最需要注意就是要更新head，tail，size

// 创建节点
class LinkNode{
    constructor(val,next){
        this.val=val
        this.next=next
    }
}

// 初始化节点
var MyLinkedList = function() {
this.size=0
this.head=null
this.tail=null
};


MyLinkedList.prototype.getNode = function(index) {
    if(index<0||index>=this.size)return null
    let ret=new ListNode(0,this.head),cur=ret
    while(index-->=0){
        cur=cur.next
    }
    return cur
};



/** 
 * @param {number} index
 * @return {number}
 */
MyLinkedList.prototype.get = function(index) {
 if(index<0||index>=this.size)return -1
 return this.getNode(index).val
};

/** 
 * @param {number} val
 * @return {void}
 */

MyLinkedList.prototype.addAtHead = function(val) {
let node=new LinkNode(val,this.head)
this.head=node
this.size++
if(!this.tail)this.tail=node
};

/** 
 * @param {number} val
 * @return {void}
 */
MyLinkedList.prototype.addAtTail = function(val) {
    let node=new LinkNode(val,null)
    this.size++
    if(!this.tail){this.tail=node;this.head = node; return}
    this.tail.next=node;this.tail = node;
};

/** 
 * @param {number} index 
 * @param {number} val
 * @return {void}
 */
MyLinkedList.prototype.addAtIndex = function(index, val) {
    if(index<=0){ this.addAtHead(val);return}
    if(index>this.size)return
    if(index===this.size){this.addAtTail(val);return}
    let node=this.getNode(index-1)
     let ret=new ListNode(val,node.next)
    node.next=ret
   this.size++
};

/** 
 * @param {number} index
 * @return {void}
 */
MyLinkedList.prototype.deleteAtIndex = function(index) {
    // 1、可能删除头节点，头节点又可能是尾节点
    // 2、先获取目标节点的上一个节点，再可能是尾节点
    if(index<0||index>=this.size)return 
    if(index===0){
        this.head=this.head.next
        if(this.size-1==0){
            this.tail=this.head
        }
        this.size--
        return
    }

const node=this.getNode(index-1)
node.next=node.next.next
    if(index===this.size-1){
        this.tail=node
    }
    this.size--


};

